/**
 * ━━━━━━神兽出没━━━━━━
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑, 永无BUG!
 * 　　　　┃　　　┃Code is far away from bug with the animal protecting
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━感觉萌萌哒━━━━━━
 */
package com.zkgengkun.console.controller;

import com.zkgengkun.console.service.WeChatService;
import com.zkgengkun.support.util.SHA1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author gengshikun
 * @date 2017/3/2
 */
@Controller
public class WxReceiveController {
    private Logger logger = LoggerFactory.getLogger(WxReceiveController.class);
//    @Autowired
//    private MessageService messageService;

    @Autowired
    private WeChatService weChatService;

    @Value("${wx.token}")
    private String wx_token;

    @RequestMapping(value = "get_code")
    @ResponseBody
    public String getCode(HttpServletResponse response){
        this.weChatService.getCode(response);
        return "success";
    }

    @RequestMapping(value = "get_access_token")
    @ResponseBody
    public String getAccessToken(HttpServletRequest request, HttpServletResponse response){
        this.weChatService.getAccessToken(request, response);
        return "success";
    }

    @SuppressWarnings({"unchecked"})
    @RequestMapping("receive")
    @ResponseBody
    public void receive(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("--> MessageController.receive()");
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        if (isGet) {
            String signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            logger.info("-->接收参数 signature:" + signature + ",timestamp:" + timestamp + ",nonce:" + nonce + ",echostr:" + echostr + "");
            access(request, response);

        } else {
            try {
                // 公众号内接收用户消息
//                this.messageService.acceptMessage(request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        logger.info("<-- MessageController.receive()");
    }

    /**
     * 验证URL真实性
     *
     * @param request
     * @param response
     * @return String
     * @author morning
     * @date 2015年2月17日 上午10:53:07
     */
    private String access(HttpServletRequest request, HttpServletResponse response) {
        // 验证URL真实性
        String signature = request.getParameter("signature");// 微信加密签名
        String timestamp = request.getParameter("timestamp");// 时间戳
        String nonce = request.getParameter("nonce");// 随机数
        String echostr = request.getParameter("echostr");// 随机字符串
        logger.info("-->MessageController.access( signature:" + signature + ",timestamp:" + timestamp + ",nonce:" + nonce + ",echostr:" + echostr + ")");

        List<String> params = new ArrayList<String>();
        params.add(wx_token);
        params.add(timestamp);
        params.add(nonce);
        // 1. 将token、timestamp、nonce三个参数进行字典序排序
        Collections.sort(params, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
        String temp = SHA1.encode(params.get(0) + params.get(1) + params.get(2));
        logger.info("请求signature:" + signature + "|加密signature:" + temp);
        if (temp.equals(signature)) {
            try {
                response.getWriter().write(echostr);
                logger.info("<--MessageController.access( signature:" + signature + ",timestamp:" + timestamp + ",nonce:" + nonce + ",echostr:" + echostr + ") 成功！");
                return echostr;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        logger.info("<--MessageController.access( signature:" + signature + ",timestamp:" + timestamp + ",nonce:" + nonce + ",echostr:" + echostr + ") 失败！ ");
        return null;
    }

}
